package manage.action;

import m.common.action.ActionMeta;
import m.common.action.VueResult;
import m.common.model.util.ModelQueryList;
import m.common.model.util.ModelUpdateUtil;
import m.common.model.util.QueryCondition;
import m.html.VueFormResult;
import m.html.VueListResult;
import m.html.element.attr.Align;
import m.html.element.attr.ButtonType;
import m.html.element.other.DisplayItem;
import m.html.element.other.Param;
import m.html.form.*;
import m.html.list.*;
import m.system.cache.CacheUtil;
import m.system.util.JSONMessage;
import m.system.util.StringUtil;
import manage.model.*;
import manage.service.AdminGroupService;
import manage.util.DictionaryUtil;

import java.util.ArrayList;
import java.util.List;

@ActionMeta(name="manage/adminGroup")
public class AdminGroupAction extends StatusAction {
	public AdminGroup model;
	private String adminOid;

	/**
	 * 获取我兼职的机构部门
	 */
	public JSONMessage getMyOrgGroup() throws Exception {
		JSONMessage result=new JSONMessage(0);
		AdminLogin admin=verifyAdminLogin();
		if(null==getSessionAssist()) {
			result.push("list", getService(AdminGroupService.class).getOrgList(admin.getOid()));
		}else{
			result.push("list",new ArrayList<String>());
		}
		return result;
	}
	public JSONMessage getMyOrgOption() throws Exception {
		List<DisplayItem> items=new ArrayList<>();
		AdminLogin admin=verifyAdminLogin();
		if(null==getSessionAssist()) {
			List<AdminGroup> orgs=getService(AdminGroupService.class).getOrgList(admin.getOid());
			for(AdminGroup org : orgs){
				items.add(DisplayItem.value(org.getOid(),org.getParent().getName()+"/"+org.getName()));
			}
		}
		return DictionaryUtil.toDictData(items);
	}
	/**
	 * 设置我当前兼职的机构部门
	 */
	public JSONMessage setCurrentOrgGroup() throws Exception {
		AdminLogin admin=verifyAdminLogin();
		admin.setOrgGroup(new OrgGroupView());
		admin.getOrgGroup().setOid(model.getOid());
		ModelUpdateUtil.updateModel(admin, "orgGroup.oid");
		setSessionOrgGroupId(model.getOid());
		CacheUtil.clear(AdminLogin.class, admin.getOid());
		return new JSONMessage(0);
	}
	public JSONMessage getList() throws Exception {
		verifyAdminOperPower("manage_system_power");
		return new JSONMessage(0)
				.push("list", getService(AdminGroupService.class).getList(model));
	}
	public JSONMessage getGroup4Admin() throws Exception {
		verifyAdminOperPower("manage_system_power");
		return new JSONMessage(0)
				.push("groupList", getService(AdminGroupService.class).getList4Admin(adminOid));
	}

	/**
	 * 保存
	 */
	public JSONMessage doSave() throws Exception {
		systemLog("组"+model.getType(),"保存用户组信息");
		verifyAdminOperPower("manage_system_power");
		String msg=getService(AdminGroupService.class).save(model);
		return new JSONMessage(0,msg)
				.push("model", model);
	}
	public VueResult toEdit() throws Exception {
		verifyAdminOperPower("manage_system_power");
		if(null!=model&&!StringUtil.isSpace(model.getOid())){
			model=ModelQueryList.getModel(model,"*");
		}else if(null==model){
			model=new AdminGroup();
			model.setBusiness("B");
			model.setType("A");
		}
		if(StringUtil.isSpace(model.getBusiness())) model.setBusiness("B");
		if(null!=model.getParent()) {
			model.setParent(ModelQueryList.getModel(model.getParent(), "*"));
		}
		ModelForm form = new ModelForm("编辑",2);
		form.setSubTitle("{{decode(model.type,'A','管理员组信息','B','角色信息','C','机构信息')}}");
		form.addItem(
			FormTest.test("model.parent&&model.parent.oid",
				FormInput.selectOneModel("父机构","model","parent",
					"'"+actionUrl("selectOrgPage")+"?params[parentOid]='+(model.parent.parent.oid||model.parent.oid)+'&params[selected]='+model.parent.oid+'&params[disabled]='+model.oid",
					"{{model.parent.name}} {{model.parent.num}}").setSpan(2)
			),
			FormInput.input("名称", "model.name").setPlaceholder("请输入名称").setRequired(true),
			FormTest.test("model.oid",FormHtml.ins("编号","{{model.num}}"))
			.other(FormInput.input("编号", "model.num").setPlaceholder("请输入编号").setRequired(true).setDescription("编号唯一，保存后不可修改。")),
			FormInput.radio("类型", "model.business", "manage.model.AdminGroup!business"),
			FormInput.integer("排序", "model.sort").setPlaceholder("请输入排序"),
			FormInput.textarea("描述", "model.description").setPlaceholder("请输入描述").setSpan(2)
		)
		.addData("model",model)
		.addButton(
			FormButton.pri("保存","doSave")
		)
		.addMethod(
			FormEvent.backTrue,
			FormEvent.doJson("doSave", actionUrl("doSave"),"{model:this.model}")
				.success("backTrue")
		);
		VueFormResult result=new VueFormResult();
		return result.addForm(form);
	}
	public VueResult selectOrgPage() throws Exception {
		boolean power=hasAdminOperPower(getStatusPower());
		VueListResult result=getVueListResult("选择父机构",AdminGroup.class,actionUrl("selectOrgPage"));
//		result.setFunction(true,true);
		result.addQueryFields("oid","parent.oid");
		result.addCol(toIndexColumn());
		result.addCol(toTextColumn("上级", "parent.name",true));
		result.addCol(toTextColumn("名称", "name",150,true));
		result.addCol(toTextColumn("编号", "num",true).setSort(true));
		result.addCol(toTextColumn("类型", "business",true).setDictOption(AdminGroup.class,"business"));
		result.addCol(toTextColumn("排序", "sort",50).setSort(ListSortOrder.ASC)
				.setFieldExpression("case when #{parent.oid} is null or #{parent.oid}='' then null else #{sort} end"));
		result.addCol(toSpaceColumn("选择",50,
			ListElement.test("record.oid!='"+getParamsValue("selected")+"'&&record.oid!='"+getParamsValue("disabled")+"'",
				ListButton.back("选择",ButtonType.PRIMARY).addParam("","")
			),
			ListElement.test("record.oid=='"+getParamsValue("selected")+"'",
				ListElement.dot("已选","red"))
		));
		result.addCondition(QueryCondition.eq("type", "C"));
		String parentOid=getParamsValue("parentOid","xxx");
		result.addCondition(QueryCondition.or(
			QueryCondition.eq("oid",parentOid),
			QueryCondition.eq("parent.oid",parentOid)
		));
		result.addCondition(QueryCondition.or(
			QueryCondition.eq(new String[]{"org.oid","oid"}),
			QueryCondition.eq(new String[]{"dept.oid","oid"})
		));
		return result;
	}
	/**
	 * 权限组设置
	 */
	public VueResult adminGroupList() throws Exception {
		verifyMenu("A1101");
		boolean power=hasAdminOperPower(getStatusPower());
		VueListResult result=getVueListResult("管理员组",AdminGroup.class,actionUrl("adminGroupList"));
		result.setSubTitle("编辑管理员组，配置管理员组权限。");
		result.setHeight(-1);
		result.setPageSize(20);
		result.addCol(toIndexColumn());
		result.addCol(toTextColumn("名称", "name",true));
		result.addCol(toTextColumn("编号", "num",true).setSort(true));
		//result.addCol(toTextColumn("类型", "business",true).setDictOption(AdminGroup.class,"business"));
		result.addCol(toTextColumn("描述", "description",150,true));
		result.addCol(toTextColumn("排序", "sort",50).setSort(ListSortOrder.DESC));
		result.addCol(toStatusColumn(power,true));
		if(power) result.addCol(toSpaceColumn("操作",200,
			ListButton.modal("修改", ButtonType.PRIMARY,actionUrl("toEdit"),700, SuccessMethod.REFRESH)
				.addParam("model.oid","oid"),
			ListDropdown.def("权限").add(
				ListButton.modal("菜单设置",ButtonType.DEFAULT,"page/base/setGroupMenuPage.js",700)
					.addParam("groupOid", "oid"),
				ListButton.modal("权限设置",ButtonType.DEFAULT,"page/base/setAdminGroupPowerPage.js",700)
					.addParam("groupOid", "oid")
			),
			ListButton.modal("管理员",ButtonType.LINK,actionUrl(AdminLoginAction.class,"adminLoginList"),1200)
				.addParam("params[adminGroupOid]", "oid")
		).setFixed(Align.RIGHT));
		if(power) result.addButton(ListButton.modal("添加",ButtonType.PRIMARY,actionUrl("toEdit"),700,SuccessMethod.REFRESH)
				.addQueryParam(Param.value("model.type","A")).addQueryParam(Param.value("model.business", "B")));

		result.addCondition(QueryCondition.eq("type", "A"));
		return result;
	}
	/**
	 * 角色列表设置
	 * 
	 *  Exception
	 */
	public VueResult adminRoleList() throws Exception {
		verifyMenu("A1103");
		boolean power=hasAdminOperPower(getStatusPower());
		VueListResult result=getVueListResult("角色设置",AdminGroup.class,actionUrl("adminRoleList"));
		result.setSubTitle("编辑角色组，配置角色组权限。");
		result.setHeight(-1);
		result.setPageSize(20);
		result.addCol(toIndexColumn());
		result.addCol(toTextColumn("名称", "name",true));
		result.addCol(toTextColumn("编号", "num",true).setSort(true));
		result.addCol(toTextColumn("类型", "business").setDictOption(AdminGroup.class,"business"));
		result.addCol(toTextColumn("描述", "description",true));
		result.addCol(toTextColumn("排序", "sort",50).setSort(ListSortOrder.DESC));
		result.addCol(toStatusColumn(power,true));
		if(power) result.addCol(toSpaceColumn("操作",220,
			ListButton.modal("修改",ButtonType.LINK,actionUrl("toEdit"),700,SuccessMethod.REFRESH)
				.addParam("model.oid","oid"),
			ListButton.modal("关联用户",ButtonType.PRIMARY,"page/base/setAdminGroupLinkAndOrgPage.js",1000,SuccessMethod.REFRESH)
				.addParam("adminGroupOid","oid"),
			ListDropdown.def("权限").add(
				ListButton.modal("菜单设置",ButtonType.DEFAULT,"page/base/setGroupMenuPage.js",700)
					.addParam("groupOid", "oid"),
				ListButton.modal("权限设置",ButtonType.DEFAULT,"page/base/setAdminGroupPowerPage.js",700)
					.addParam("groupOid", "oid")
			)
		));
		if(power) result.addButton(ListButton.modal("添加",ButtonType.PRIMARY,actionUrl("toEdit"),700,SuccessMethod.REFRESH)
				.addQueryParam(Param.value("model.type","B")).addQueryParam(Param.value("model.business", "B")));
		
		result.addCondition(QueryCondition.eq("type", "B"));
		return result;
	}

	@Override
	public void doRecoveryCallback() {
		DictionaryUtil.clear(AdminGroup.class);
		DictionaryUtil.clear(OrgGroupView.class);
		CacheUtil.clear(ModuleInfo.class);//清楚模块缓存
		CacheUtil.clear(MenuInfo.class);//清楚菜单缓存
	}

	@Override
	public void doDisableCallback() {
		DictionaryUtil.clear(AdminGroup.class);
		DictionaryUtil.clear(OrgGroupView.class);
		CacheUtil.clear(ModuleInfo.class);//清楚模块缓存
		CacheUtil.clear(MenuInfo.class);//清楚菜单缓存
	}

	@Override
	public String[] getStatusPower() {
		return new String[]{"manage_system_power"};
	}

	public String getAdminOid() {
		return adminOid;
	}
	public void setAdminOid(String adminOid) {
		this.adminOid = adminOid;
	}
	public AdminGroup getModel() {
		return model;
	}

	public void setModel(AdminGroup model) {
		this.model = model;
	}

}
